import { reactive, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';
import page from './page.ts';
import { useRouter, useRoute } from 'vue-router';
import { getRoles } from '@/utils/optionsArr.ts';
export function useListComponent() {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;
  const options = reactive({
    //启用状态
    state: [
      {
        label: '启用',
        value: 1,
        type: 'success',
      },
      {
        label: '禁用',
        value: 2,
        type: 'info',
      },
    ],
    roles: [], //角色权限
    employeeType: [], //员工类型
    employeeState: [], //员工类型
    nation: [], //民族
    residenceType: [], //户籍类型
    politicsStatus: [], //政治面貌
    maritalStatus: [], //婚姻状况
    qualification: [], //学历
  });
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    //分类
    tabs: {
      title: '企业部门', //分类
      search: '', //搜索
      activeKey: 'departmentCode', //唯一值key
      titleKey: 'departmentName', //唯一值key
      active: '', //选中值
      organizationCode: '', //机构唯一值key
      list: [], //数据
      //分类操作
      operation: [
        {
          title: '编辑',
          icon: 'Edit',
          permission: 'MenuCode7-1-4',
          click: (row: any, index: number) => {
            proxy.$messageInputBox(`修改部门【${row.departmentName}】`, (value: string) => {
              proxy.$api.Department.UpdateDepartment({
                ...row,
                departmentName: value,
              })
                .then((res: any) => {
                  proxy.$message('修改成功');
                  getTabs();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '删除',
          icon: 'Delete',
          permission: 'MenuCode7-1-5',
          click: (row: any, index: number) => {
            proxy.$messageBox('是否删除当前数据，请确认！', () => {
              proxy.$api.Department.DeleteDepartment({
                entityID: row.departmentID, //	对象主键ID
                entityCode: row.departmentCode, //对象唯一识别码
              })
                .then((res: any) => {
                  getTabs();
                })
                .catch(() => {});
            });
          },
        },
      ],
      //分类点击列表
      click: (row: any, index: number) => {
        clickTabs(row);
      },
      add: {
        permission: 'MenuCode7-1-1',
        //分类新建按钮
        click: () => {
          proxy.$messageInputBox(`请填写新的部门名称`, (value: string) => {
            proxy.$api.Department.AddDepartment({
              OrganizationCode: dataInfo.tabs.organizationCode,
              departmentName: value,
            })
              .then((res: any) => {
                proxy.$message('新建成功');
                getTabs();
              })
              .catch(() => {});
          });
        },
      },
    },
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: 'employeeID',
      theadCode: 'employeelist', //basedatatable
      //表格-表头数据
      thead: [],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 30, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: '', // 关键字查询字段，空值查询全部
        likeWords: '', // 查询关键字，空值查询全部
        beginTime: '', // 日期范围-开始时间
        endTime: '', // 日期范围-结束时间
        onlySelf: 0, // 是否只查询自己创建的，0：查所有、1：只查自己创建的
        isShowDisabled: -1, // 是否显示禁用,-1：显示所有的；0：仅显示未作废的；1 仅显示作废的
        orderByFiled: '', // 排序字段
        orderByType: 0, // 排序方式，0-倒序,1-升序
        departmentCode: '', // 部门编码(传空查全部)
      },
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.Business.GetMatchPageEmployees({
                  ...dataInfo.table.search,
                  pageIndex: 1,
                  pageSize: 10000,
                })
                  .then((res: any) => {
                    exportBtn(res.list);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
      ],
      //列表双击
      // dblclick: (row: any) => {
      //   editBtn(row);
      // },
      //表格-列表搜索
      operation: [
        {
          title: '编辑',
          permission: 'MenuCode7-1-4',
          click: (row: any) => {
            getPath({
              path: `${route.path}/details`,
              query: {
                type: 2,
                employeeID: row.employeeID,
              },
            });
          },
        },
        {
          title: (row: any) => {
            return row.accountState === 1 ? '禁用' : '启用';
          },
          permission: 'MenuCode7-1-2', //是有权限
          click: (row: any, index: number) => {
            proxy.$api.Business.ExcuteUpdateManageAccountState({
              employeeCode: row.employeeCode,
              isEnabled: row.accountState === 2,
            })
              .then((res: any) => {
                ElMessage({
                  message: `${row.accountState === 1 ? '禁用' : '启用'}成功`,
                  type: 'success',
                });
                getTbody();
              })
              .catch(() => {});
          },
        },
        {
          title: '重置密码',
          permission: 'MenuCode7-1-6',
          click: (row: any, index: number) => {
            proxy.$messageBox('是否重置当前数据密码，请确认！', () => {
              proxy.$api.Business.ExcuteResetLoginPassWord({
                employeeCode: row.employeeCode,
              })
                .then((res: any) => {
                  proxy.$message('重置成功,新的密码是123456');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '删除',
          permission: 'MenuCode7-1-5',
          click: (row: any, index: number) => {
            proxy.$messageInputBox(
              `请输入“同意删除”以确认删除操作`,
              (value: string) => {
                proxy.$api.Business.DeleteEmployee({
                  entityID: row.employeeID,
                  entityCode: row.employeeCode,
                })
                  .then((res: any) => {
                    proxy.$message('删除成功');
                    getTbody();
                  })
                  .catch(() => {});
              },
              {
                inputPattern: /同意删除/,
                inputErrorMessage: '请输入正确的确认信息（同意删除）',
              },
            );
          },
        },
      ],
    },
  });
  // 获取tabs数据
  // 获取tabs数据
  const editBtn = (row: any) => {
    getPath({
      path: `${route.path}/details`,
      query: row,
    });
  };
  // 获取tabs数据
  const getPath = (obj: any, row?: any) => {
    const path = router.resolve(obj);
    // 在新窗口或标签页中打开目标路径
    const newWindow: any = window.open(path.href, '_blank');
    newWindow;
  };
  // 获取tabs数据
  const getTabs = () => {
    proxy.$api.Organization.GetAllOrganizations().then((res: any) => {
      dataInfo.tabs.organizationCode = res[0].orgCode;
      proxy.$api.Department.GetDepartmentTreeData({
        orgCode: res[0].orgCode, //组织唯一识别码
      }).then((res: any) => {
        res.unshift({
          isAll: true,
          departmentName: '全部',
          departmentCode: '',
        });
        dataInfo.tabs.list = res;
        if (!dataInfo.tabs.active) {
          clickTabs(res[0]);
        }
      });
    });
  };
  // 获取tabs数据
  const clickTabs = (row: any) => {
    if (row) {
      dataInfo.tabs.active = row.departmentCode;
      dataInfo.table.title = `${page.title}【${row.departmentName}】`;
      dataInfo.table.checkbox.list = [];
      getTbody();
    }
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.Business.GetMatchPageEmployees({
      ..._table.search,
      departmentCode: dataInfo.tabs.active, //部门编码
      organizationCode: dataInfo.tabs.organizationCode, //机构编码
    })
      .then((res: any) => {
        _table.tbody = res.list;
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 导出数据
  const exportBtn = (tbody: any[]) => {
    proxy.$exportData(
      {
        thead: dataInfo.table.thead,
        tbody: tbody,
        fileName: dataInfo.table.title,
      },
      dataInfo,
    );
    setTimeout(() => {
      dataInfo.loading = false;
    }, 1000);
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  onMounted(() => {
    getRoles(options, 'roles'); //获取所有客户
  });
  // 组件挂载后执行
  onMounted(() => {
    getTabs();
  });
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, options };
}
